package com.lw.service.impl;

import com.lw.common.utils.StrUtils;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.lw.entity.TbDictItem;
import com.lw.mapper.TbDictItemMapper;
import com.lw.service.TbDictItemService;
import org.springframework.stereotype.Service;

import java.security.UnresolvedPermission;
import java.util.List;

import static com.lw.entity.table.TbDictItemTableDef.TB_DICT_ITEM;

/**
 * 字典项表 服务层实现。
 *
 * @author lw
 * @since 2025年05月17日 07:58:04
 */
@Service
public class TbDictItemServiceImpl extends ServiceImpl<TbDictItemMapper, TbDictItem>  implements TbDictItemService{

    @Override
    public List<TbDictItem> listByDictCode(String dictCode) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select(TB_DICT_ITEM.LABEL,TB_DICT_ITEM.VALUE, TB_DICT_ITEM.TAG_TYPE);
        queryWrapper.eq(TB_DICT_ITEM.DICT_CODE.getName(), dictCode);
        return list(queryWrapper);
    }

    @Override
    public Page<TbDictItem> getDictItemPage(TbDictItem dictItem) {
        Page<TbDictItem> page = new Page<>();
        page.setPageNumber(dictItem.getPageNum());
        page.setPageSize(dictItem.getPageSize());
        //判断字典码不能为空
        if (StrUtils.isEmpty(dictItem.getDictCode())) {
            throw new RuntimeException("字典码不能为空");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(TB_DICT_ITEM.DICT_CODE.getName(), dictItem.getDictCode());
        return page(page, queryWrapper);
    }

    @Override
    public Boolean saveItem(TbDictItem tbDictItem) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(TB_DICT_ITEM.DICT_CODE.getName(), tbDictItem.getDictCode());
        queryWrapper.eq(TB_DICT_ITEM.VALUE.getName(), tbDictItem.getValue());
        long count = count(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("字典项和值已重复");
        }
        return save(tbDictItem);
    }

    @Override
    public Boolean updateItem(TbDictItem tbDictItem) {
        return  updateById(tbDictItem);
    }
}
